package com.gate.ws.spring.network.factory;


import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyEventLoopFactory {

    public static EventLoopGroup createEventLoopGroup(int threads, String threadFactoryName) {
        NamedThreadFactory namedThreadFactory = new NamedThreadFactory(threadFactoryName);
        return enableEpoll() ? new EpollEventLoopGroup(threads, namedThreadFactory) :
            new NioEventLoopGroup(threads, namedThreadFactory);
    }

    public static Class<? extends SocketChannel> createSocketChannelClass() {
        return enableEpoll() ? EpollSocketChannel.class : NioSocketChannel.class;
    }

    public static Class<? extends ServerSocketChannel> createServerSocketChannelClass() {
        return enableEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class;
    }

    public static Class<? extends DatagramChannel> createDatagramChannelClass() {
        return enableEpoll() ? EpollDatagramChannel.class : NioDatagramChannel.class;
    }

    private static boolean enableEpoll() {
        if (Epoll.isAvailable()) {
            return isLinux();
        }
        return false;
    }

    private static boolean isLinux() {
        String osName = System.getProperty("os.name").toLowerCase();
        return osName.contains("linux");
    }
}
